<template>
  <div ref="treeBox" @click="aaa = '2'">
    <div>
      <!-- 树形结构 -->
      <!-- show-checkbox -->
      <!-- @check-change="handleCheckChange" -->
      <el-row>
        <el-col :span="16">
          <el-card class="box-card">
            <el-input
              class="select_input"
              placeholder="输入关键字进行过滤"
              v-model="filterText"
            ></el-input>
            <!-- <abbr title="添加分组">
            <el-button class="u-add-parent" type="primary" icon="el-icon-plus" circle></el-button>
          </abbr>
          <abbr title="删除选中">
            <el-button class="u-delect-all" type="danger" icon="el-icon-delete" circle></el-button>
            </abbr>-->
            <el-tree
              :data="treeData"
              node-key="t_id"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
            >
              <div class="custom-tree-node" slot-scope="{ node, data }">
                <div class="z-inline">{{ node.label }}</div>
                <div class="z-inline">
                  <el-popover
                    ref="popoverUpdate"
                    trigger="click"
                    placement="right"
                    title="移动节点"
                    width="600"
                    content
                  >
                    <div>
                      <el-form
                        :model="ruleFormUpdate"
                        :rules="rulesMoveForm"
                        :ref="'moveDom' + node.id"
                        label-width="100px"
                        class="demo-ruleForm"
                      >
                        <el-form-item label="节点目录" prop="parent">
                          <el-popover
                            placement="right"
                            width="400"
                            trigger="hover"
                          >
                            <el-tree
                              :data="treeDataCopy"
                              @node-click="handleNodeClick"
                            ></el-tree>
                            <a slot="reference">{{ moveForm.lable }}</a>
                          </el-popover>
                        </el-form-item>
                        <el-form-item>
                          <el-button
                            type="primary"
                            @click="moveDomNow('moveDom' + node.id)"
                            >确定</el-button
                          >
                          <el-button @click="close()">取消</el-button>
                        </el-form-item>
                      </el-form>
                    </div>
                    <el-button
                      slot="reference"
                      type="text"
                      size="mini"
                      @click.stop="() => moveDom(node, data)"
                      >移动</el-button
                    >
                  </el-popover>
                  <el-popover
                    ref="popoverAdd"
                    placement="bottom"
                    title="添加选项"
                    width="500"
                    trigger="click"
                  >
                    <div>
                      <el-form
                        :model="ruleFormAdd"
                        :rules="rulesAdd"
                        :ref="'addDom' + node.id"
                        label-width="100px"
                        class="demo-ruleForm"
                      >
                        <el-form-item label="添加名称" prop="name">
                          <el-input v-model="ruleFormAdd.name"></el-input>
                        </el-form-item>
                        <el-form-item label="添加说明">
                          <el-input
                            v-model="ruleFormAdd.description"
                          ></el-input>
                        </el-form-item>
                        <el-form-item label="唯一标识">
                          <el-input v-model="ruleFormAdd.real_value"></el-input>
                        </el-form-item>
                        <el-form-item>
                          <el-button
                            type="primary"
                            @click="appendUrl('addDom' + node.id)"
                            >添加</el-button
                          >
                          <el-button @click="close()">取消</el-button>
                        </el-form-item>
                      </el-form>
                    </div>
                    <el-button
                      slot="reference"
                      type="text"
                      size="mini"
                      @click="() => append(data)"
                      >添加</el-button
                    >
                  </el-popover>
                  <el-popover
                    ref="popoverUpdate"
                    trigger="click"
                    placement="right"
                    title="修改选项"
                    width="500"
                    content
                  >
                    <div>
                      <el-form
                        :model="ruleFormUpdate"
                        :rules="rulesUpdate"
                        :ref="'updateDom' + node.id"
                        label-width="100px"
                        class="demo-ruleForm"
                      >
                        <el-form-item label="新名称" prop="name">
                          <el-input v-model="ruleFormUpdate.name"></el-input>
                        </el-form-item>
                        <el-form-item label="修改说明">
                          <el-input
                            v-model="ruleFormUpdate.description"
                          ></el-input>
                        </el-form-item>
                        <el-form-item label="唯一标识">
                          <el-input
                            v-model="ruleFormUpdate.real_value"
                          ></el-input>
                        </el-form-item>
                        <el-form-item>
                          <el-button
                            type="primary"
                            @click="updateUrl('updateDom' + node.id)"
                            >修改</el-button
                          >
                          <el-button @click="close()">取消</el-button>
                        </el-form-item>
                      </el-form>
                    </div>
                    <el-button
                      slot="reference"
                      type="text"
                      size="mini"
                      @click="() => update(node, data)"
                      >修改</el-button
                    >
                  </el-popover>
                  <el-button
                    type="text"
                    size="mini"
                    @click="() => remove(node, data)"
                    >删除</el-button
                  >
                </div>
              </div>
            </el-tree>
          </el-card>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple-light"></div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import { getTree, tableInsert, tableUpdate } from '@/api/api.js';
export default {
  data() {
    return {
      node_in: {},
      data_in: {},
      rulesMoveForm: {
        // parent: [{ required: true, message: '请选择新节点', trigger: 'blur' }]
      },
      moveForm: {
        lable: '请选择',
        parent: '',
        moveId: '',
      },
      aaa: '',
      addDataSet: {},
      updateDataSet: {},
      filterText: '',
      treeData: [],
      treeDataCopy: [],
      ruleFormAdd: {
        name: '',
        description: '',
        real_value: '',
      },
      rulesAdd: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            min: 1,
            max: 100,
            message: '长度在 1 到 100 个字符',
            trigger: 'blur',
          },
        ],
      },
      ruleFormUpdate: {
        name: '',
        description: '',
        real_value: '',
      },
      rulesUpdate: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            min: 1,
            max: 100,
            message: '长度在 1 到 100 个字符',
            trigger: 'blur',
          },
        ],
      },
    };
  },
  created() {
    this.getTreeUrl();
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    // 移动目录交互请求
    async moveDomNow(e) {
      if (this.moveForm.parent) {
        // 修改接口
        let res = await tableUpdate([
          {
            table_name: 'nice_enum_tree',
            update: [
              {
                parent: this.moveForm.parent,
              },
            ],
            where: [
              {
                t_id: this.moveForm.moveId,
              },
            ],
          },
        ]);
        if (res[0]) {
          return;
        }
        let dataCopy = JSON.parse(JSON.stringify(this.data_in));
        const parent = this.node_in.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex((d) => d.t_id === this.data_in.t_id);
        children.splice(index, 1);
        this.addDataSet.children.push(dataCopy);
        this.close();
      } else {
        this.$message('您未选择节点');
      }
    },
    // 移动目录选中节点
    handleNodeClick(e) {
      this.moveForm.lable = e.label;
      this.moveForm.parent = e.t_id;
      this.addDataSet = e;
    },
    // 配置移动数据
    moveDom(node, data) {
      this.moveForm.lable = '请选择';
      this.moveForm.parent = '';
      this.moveForm.moveId = data.t_id;
      this.node_in = node;
      this.data_in = data;
      this.treeDataCopy = this.treeData;
    },
    close() {
      this.$refs.treeBox.click();
    },

    async getTreeUrl() {
      let res = await getTree({ id: '1', tableName: 'nice_enum_tree' });
      if (res[0]) {
        return;
      }
      // console.log(res[1], '11111')
      this.treeData = JSON.parse(
        JSON.stringify([res[1].data])
          .split('child')
          .join('children')
      );
      this.treeData = JSON.parse(
        JSON.stringify(this.treeData)
          .split('display_value')
          .join('label')
      );
      this.treeDataCopy = this.treeData;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 添加节点
    append(data) {
      this.addDataSet = data;
    },
    appendUrl(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const newChild = {
            label: this.ruleFormAdd.name,
            description: this.ruleFormAdd.description,
            real_value: this.ruleFormAdd.real_value,
            children: [],
          };
          // 添加接口
          let res = await tableInsert([
            {
              table_name: 'nice_enum_tree',
              list: [
                {
                  display_value: this.ruleFormAdd.name,
                  description: this.ruleFormAdd.description,
                  real_value: this.ruleFormAdd.real_value,
                  parent: this.addDataSet.t_id,
                },
              ],
            },
          ]);
          if (res[0]) {
            return;
          }
          //
          newChild.t_id = res[1].data[0].list[0].id;
          if (!this.addDataSet.children) {
            this.$set(this.addDataSet, 'children', []);
          }
          this.addDataSet.children.push(newChild);
          this.close();
          this.ruleFormAdd = {
            name: '',
            description: '',
            real_value: '',
          };
          this.treeDataCopy = this.treeData;
        } else {
          this.$message('输入的内容检测不合理');
          return false;
        }
      });
    },
    // 修改节点
    update(node, data) {
      this.updateDataSet = data;
      this.ruleFormUpdate = {
        name: data.label,
        description: data.description,
        real_value: data.real_value,
      };
    },
    // 修改请求
    updateUrl(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 修改接口
          let res = await tableUpdate([
            {
              table_name: 'nice_enum_tree',
              update: [
                {
                  display_value: this.ruleFormUpdate.name,
                  description: this.ruleFormUpdate.description,
                  real_value: this.ruleFormUpdate.real_value,
                },
              ],
              where: [
                {
                  t_id: this.updateDataSet.t_id,
                },
              ],
            },
          ]);
          if (res[0]) {
            return;
          }
          //
          this.updateDataSet.label = this.ruleFormUpdate.name;
          this.updateDataSet.description = this.ruleFormUpdate.description;
          this.updateDataSet.real_value = this.ruleFormUpdate.real_value;
          // this.getTreeUrl()
          //
          this.close();
          this.ruleFormUpdate = {
            name: '',
            description: '',
            real_value: '',
          };
        } else {
          this.$message('输入的内容检测不合理');
          return false;
        }
      });
    },
    // 选择
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
    },
    remove(node, data) {
      this.$confirm('确认要删除？')
        .then(async (_) => {
          let res = await tableUpdate([
            {
              table_name: 'nice_enum_tree',
              update: [
                {
                  enable: '1',
                },
              ],
              where: [
                {
                  t_id: data.t_id,
                },
              ],
            },
          ]);
          if (res[0]) {
            return;
          }
          // this.getTreeUrl()
          const parent = node.parent;
          const children = parent.data.children || parent.data;
          const index = children.findIndex((d) => d.t_id === data.t_id);
          children.splice(index, 1);
        })
        .catch((_) => {});
    },
  },
};
</script>
<style scoped>
.select_input {
  margin-bottom: 10px;
}
.u-add-parent {
  transform: scale(0.7);
}
.u-delect-all {
  margin-left: -10px;
  transform: scale(0.7);
}
.z-inline {
  line-height: 40px;
}
.custom-tree-node {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>
